<?php


namespace Aoe\Emulator\Pascal;


use Aoe\Emulator\Ifc\Type;
use function convert_float;

class Decimal extends Pascal
{
    public function afterLoad($value): mixed
    {
        $this->convert($value);
        return $value;
    }
    
    protected function valid_core(mixed &$value, string $operator = '=', bool $calculate = true): bool
    {
        return $this->convert($value);
    }

    /**
     * @param float $value
     * @return bool
     */
    protected function valid_rules(mixed $value): bool
    {
        if ($this->element->has(self::MIN) && $value < $this->_get_value_of(self::MIN)) return false;
        if ($this->element->has(self::MAX) && $value > $this->_get_value_of(self::MAX)) return false;
        return parent::valid_rules($value);
    }
    
    protected function convert(&$value): bool
    {
        return $this->isDouble() ? convert_double($value) : convert_float($value);
    }
    
    protected function isDouble(): bool
    {
        return $this->element->get(Type::DOUBLE, false);
    }
    
    protected function _calculators(): array
    {
        return ['+', '-', '*', '/'];
    }
    
    protected function compares(): array
    {
        return $this->math_compares();
    }


    private function _get_value_of(string $key): float
    {
        return $this->isDouble()
            ? doubleval($this->element->get($key))
            : floatval($this->element->get($key));
    }
}